// utils/pay.js
import {
  createWechatOrder,
  queryWechatOrder,
  closeWechatOrder,
  refundWechatOrder,
  queryWechatRefund
} from "@/api/pay.js";

const PAY_STATE = {
  SUCCESS: 'success',
  FAIL: 'fail',
  CANCEL: 'cancel'
}

/**
 * 微信支付工具类，支持多种支付方式和支付相关接口
 */
export class WechatPay {
  constructor() {
    // 由于使用了统一的 http.request，不需要单独配置 baseUrl 和 token
    // 这些都在 utils/request.js 中统一处理
  }

  // 创建微信支付订单（jsapi/h5/native）
  async createOrder(orderId, { openid, payType = 'jsapi' } = {}) {
    return await createWechatOrder(orderId, { openid, payType });
  }

  // 查询微信支付订单
  async queryOrder(outTradeNo) {
    return await queryWechatOrder(outTradeNo);
  }

  // 关闭微信支付订单
  async closeOrder(outTradeNo) {
    return await closeWechatOrder(outTradeNo);
  }

  // 申请退款
  async refund(orderId, reason) {
    return await refundWechatOrder(orderId, reason);
  }

  // 查询退款状态
  async queryRefund(outRefundNo) {
    return await queryWechatRefund(outRefundNo);
  }

  /**
   * 通用支付入口
   * @param {Object} options { orderId, openid, payType, onSuccess, onFail, onQRCode, onPolling }
   */
  async pay(options) {
    const { orderId, openid, payType = 'jsapi', onSuccess, onFail, onQRCode, onPolling } = options;
    
    

    const result = await this.createOrder(orderId, {orderId, openid, payType });
    if (result.code !== 200) {
      onFail && onFail(result);
      return Promise.reject(result);
    }
    const data = result.data;
    if (payType === 'jsapi') {
      // 小程序/公众号内调起微信支付
      return new Promise((resolve, reject) => {
        uni.requestPayment({
          provider: 'wxpay',
          timeStamp: data.timeStamp,
          nonceStr: data.nonceStr,
          package: data.package,
          signType: data.signType || 'MD5',
          paySign: data.paySign,
          success: (res) => {
            onSuccess && onSuccess(res);
            resolve({ state: PAY_STATE.SUCCESS, data: res });
          },
          fail: (err) => {
            let state = PAY_STATE.FAIL;
            let msg = '支付失败';
            if (err.errMsg === 'requestPayment:fail cancel') {
              state = PAY_STATE.CANCEL;
              msg = '用户取消支付';
            }
            onFail && onFail({ state, msg, detail: err });
            reject({ state, msg, detail: err });
          }
        });
      });
    } else if (payType === 'h5') {
      // H5支付，直接跳转
      if (data.h5_url) {
        window.location.href = data.h5_url;
        onSuccess && onSuccess(data);
        return Promise.resolve({ state: PAY_STATE.SUCCESS, data });
      } else {
        onFail && onFail({ state: PAY_STATE.FAIL, msg: '未获取到H5支付链接' });
        return Promise.reject({ state: PAY_STATE.FAIL, msg: '未获取到H5支付链接' });
      }
    } else if (payType === 'native') {
      // Native支付，返回二维码链接
      if (data.code_url) {
        onQRCode && onQRCode(data.code_url, data);
        // 可选：轮询支付状态
        if (onPolling && typeof onPolling === 'function') {
          onPolling(data.outTradeNo);
        }
        return Promise.resolve({ state: PAY_STATE.SUCCESS, data });
      } else {
        onFail && onFail({ state: PAY_STATE.FAIL, msg: '未获取到Native支付二维码' });
        return Promise.reject({ state: PAY_STATE.FAIL, msg: '未获取到Native支付二维码' });
      }
    }
  }
}

/**
 * 兼容原有的 wxPay 方法，仅支持jsapi
 */
export const wxPay = (paymentData) => {
  return new Promise((resolve, reject) => {
    if (!paymentData ||
      !paymentData.timeStamp ||
      !paymentData.nonceStr ||
      !paymentData.package ||
      !paymentData.paySign) {
      reject({
        state: PAY_STATE.FAIL,
        msg: '支付参数不完整'
      })
      return
    }
    uni.requestPayment({
      provider: 'wxpay',
      timeStamp: paymentData.timeStamp,
      nonceStr: paymentData.nonceStr,
      package: paymentData.package,
      signType: paymentData.signType || 'MD5',
      paySign: paymentData.paySign,
      success: (res) => {
        resolve({
          state: PAY_STATE.SUCCESS,
          data: res
        })
      },
      fail: (err) => {
        const result = {
          state: PAY_STATE.FAIL,
          msg: '支付失败',
          detail: err
        }
        if (err.errMsg === 'requestPayment:fail cancel') {
          result.state = PAY_STATE.CANCEL
          result.msg = '用户取消支付'
        }
        reject(result)
      }
    })
  })
}

// 挂载到全局
export default {
  install: (Vue, options = {}) => {
    // 由于使用了统一的 http.request，不需要传递 baseUrl 和 token
    Vue.prototype.$wxPay = wxPay
    Vue.prototype.$WechatPay = new WechatPay()
  }
}